// 用position实现

export default function bindDirective (Vue) {
  Vue.directive('scroll', {
    bind: function (el, binding, vnode) {
      let tabs = document.createElement('div')
      tabs.classList.add('scroll-tabs')
      // 给el加翻页按钮
      for (let i = 0; i < el.children.length; i++) {
        let tab = document.createElement('div')
        tab.classList.add('scroll-tab-item')
        if (i == 0) {
          tab.classList.add('active')
        }
        // 翻页按钮的点击事件
        tab.onclick = () => {
          for (let i = 0; i < el.children.length - 1; i++) {
            const elm = el.querySelectorAll('.scroll-tab-item')[i]
            if (elm.classList.contains('active')) {
              elm.classList.remove('active')
            }
          }
          el.querySelectorAll('.scroll-tab-item')[i].classList.add('active')
        }
        tabs.append(tab)
      }
      el.append(tabs)
      const isShow = (parent, child)=>{
        return ((child.offsetTop + child.offsetHeight > parent.scrollTop) &&
                (child.offsetTop < parent.scrollTop))
      };
      el.onscroll = function () {
        for (let i = 0; i < el.children.length - 1; i++) {
          const elm = el.querySelectorAll('.scroll-tab-item')[i]
          if (elm.classList.contains('active')) {
            elm.classList.remove('active')
          }
        }
        const parent = el
        for (let i = 0; i < el.children.length - 1; i++) {
          const child = el.children[i]
        }
      }
      // 解决浏览器缩放时导致的错位
      const onresize = () => {
        for (let i = 0; i < el.children.length - 1; i++) {
          const elm = el.querySelectorAll('.scroll-tab-item')[i]
          if (elm.classList.contains('active')) {
            el.children[i].scrollIntoView({behavior: 'smooth', block: 'start'})
            el.querySelectorAll('.scroll-tab-item')[i].classList.add('active')
          }
        }
      }
      let resizeObserver = new ResizeObserver(onresize)
      resizeObserver.observe(el)
    },
    unbind: function (el, binding, vnode) {
      el.onscroll = null
      el.onresize = null
    },
  })
}